﻿using System;
using System.IO;
using System.Windows;
using System.Windows.Browser;
using System.Windows.Media;
using System.Windows.Resources;

namespace HackingSilverlightLibrary
{
    public class Tools
    {
        public static void InsertECMAScript(string JavaScript)
        {
            HtmlElement script = HtmlPage.Document.CreateElement("script");

            script.SetAttribute("type", "text/javascript");
            script.SetProperty("text", JavaScript);

            HtmlPage.Document.DocumentElement.AppendChild(script);
        }

        public static string ReadStringResource(string ResourcePath)
        {
            StreamResourceInfo FileHandle = Application.GetResourceStream(new Uri(ResourcePath, UriKind.RelativeOrAbsolute));
            TextReader MyReader = new StreamReader(FileHandle.Stream);
            return MyReader.ReadToEnd();
        }

        public static Color GetColor(string ThisColorCode)
        {
            Color c = new Color();

            c.A = Convert.ToByte(ThisColorCode.Substring(1, 2), 16);
            c.R = Convert.ToByte(ThisColorCode.Substring(3, 2), 16);
            c.G = Convert.ToByte(ThisColorCode.Substring(5, 2), 16);
            c.B = Convert.ToByte(ThisColorCode.Substring(7, 2), 16);

            return c;
        }

        #region [ eval function ]

        private static string ClientSideEvalName = string.Empty;
        private static ScriptObject ClientSideEvalFunction = null;

        public static ScriptObject eval(string ECMACode)
        {
            if (string.IsNullOrEmpty(ClientSideEvalName))
            {
                ClientSideEvalName = "eval" + (Guid.NewGuid().ToString().Replace('-', 'x'));

                InsertECMAScript("function " + ClientSideEvalName + "(InputValue) { return eval(InputValue); }");

                ClientSideEvalFunction = (ScriptObject)HtmlPage.Window.GetProperty(ClientSideEvalName);
            }
            return (ScriptObject)(ClientSideEvalFunction.InvokeSelf(ECMACode));
        }

        #endregion

    }
}
